---
title: Creating Flows
---

Flows are containers for tasks that provide a shared context and history. Each flow corresponds to a specific "thread" which maintains the state of all LLM activity.

Every task must always be executed as part of a flow.

## Why do we need flows?

You may have noticed that we haven't needed to create flows explicitly in any of the examples so far. Tasks will automatically detect if they are being run inside a flow and create a new flow if necessary.

This is convenient for one-off tasks, but it's easy to see the limitations of the approach. Consider the following example:

<CodeGroup>
```python Code
import controlflow as cf

x = cf.run('Choose a number between 1 and 1000', result_type=int)
y = cf.run('Add 5 to the number', result_type=int)

print(x)
print(y)
print(f'The difference between x and y is {y - x}')
```

```text Result
649
5
The difference between x and y is -644
```
</CodeGroup>

Each `cf.run()` call will create a new flow, which means that the result of the first tasks will not be visible to the second task.

We can fix this by running both tasks inside a flow.

<CodeGroup>
```python Code
import controlflow as cf

with cf.Flow() as flow:
    x = cf.run('Choose a number between 1 and 1000', result_type=int)
    y = cf.run('Add 5 to the number', result_type=int)

print(x)
print(y)
print(f'The difference between x and y is {y - x}')
```

```text Result
732
737
The difference between x and y is 5
```
</CodeGroup>

Now the results are correct.